package com.zhao.leetcode.StringStudy.easy;

import java.util.Set;

/**
 * https://leetcode.cn/problems/valid-palindrome/description/?envType=study-plan-v2&envId=top-interview-150
 *
 * @program: arithmetic-do-exercise
 * @author: zhaohuan
 * @create: 2025-10-10 15:44
 * @description
 **/
public class HuiwenString {

    Set<Character> targetChars = Set.of('a',
            'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
    public static void main(String[] args) {
        System.out.println("amanaplanacanalpanama".length());
        HuiwenString huiwenString = new HuiwenString();
        System.out.println(huiwenString.isPalindromeV2("race a car"));
    }

    public boolean isPalindrome(String s) {
        if (s == null) {
            return true;
        }
        char min = 'a', max = 'z';
        int minNum = '0', maxNum = '9';

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c >= min && c <= max) {
                sb.append(c);
                continue;
            }
            if (c >= minNum && c <= maxNum) {
                sb.append(c);
                continue;
            }
            c += 32;
            if (c >= min && c <= max) {
                sb.append(c);
                continue;
            }
        }

        if (sb.length() <= 1) {
            return true;
        }
        int start = 0, end = sb.length() - 1;

        while (start < end) {
            if (sb.charAt(start++) != sb.charAt(end--)) {
                return false;
            }
        }
        return true;

    }

    public boolean isPalindromeV2(String s) {
        if (s == null) {
            return true;
        }

        int start = 0, end = s.length() - 1;
        char startC = getTargetChar(s.charAt(start));
        char endC = getTargetChar(s.charAt(end));
        while (start < end) {
            while (!targetChars.contains(startC) && start < end) {
                start ++;
                startC = getTargetChar(s.charAt(start));
            }
            while (!targetChars.contains(endC) && start < end) {
                end --;
                endC = getTargetChar(s.charAt(end));
            }
            if (startC != endC) {
                return false;
            }
            end --;
            start ++;
            startC = getTargetChar(s.charAt(start));
            endC = getTargetChar(s.charAt(end));
        }
        return true;


    }

    private char getTargetChar(char c) {

        if (targetChars.contains(c)) {
            return c;
        }
        return (char) (c + 32);
    }

}
